App({
  globalData: {
    userInfo: null,
    token: null,
    cartCount: 0,
    cartItems: [],
    baseUrl: 'https://api.guguxiang.xin/api',
    noTokenUrls: [
      '/user/login/',
      '/user/wx_login/',
      '/user/register/',
      '/product/categories/',
      '/product/products/',
      '/product/products/search/',
    ]
  },

  onLaunch() {
    // 初始化事件总线
    if (!wx.eventBus) {
      wx.eventBus = {
        listeners: {},
        emit(event, data) {
          const callbacks = this.listeners[event] || [];
          callbacks.forEach(callback => callback(data));
        },
        on(event, callback) {
          if (!this.listeners[event]) {
            this.listeners[event] = [];
          }
          this.listeners[event].push(callback);
        },
        off(event, callback) {
          const callbacks = this.listeners[event] || [];
          const index = callbacks.indexOf(callback);
          if (index > -1) {
            callbacks.splice(index, 1);
          }
        }
      };
    }

    // 获取本地存储的token
    const token = wx.getStorageSync('token');
    if (token) {
      this.globalData.token = token;
      this.updateCartCount();
    }
  },

  // 全局请求方法
  request(options) {
    const { url, method = 'GET', data, header = {} } = options;
    const fullUrl = this.globalData.baseUrl + url;

    // 检查是否需要添加认证头
    const needAuth = !this.globalData.noTokenUrls.some(path => url.startsWith(path));

    if (needAuth) {
      const token = wx.getStorageSync('token');
      if (!token) {
        // 如果需要认证但没有token，跳转到登录页
        wx.navigateTo({
          url: '/pages/login/login'
        });
        return Promise.reject(new Error('未登录'));
      }
      header.Authorization = `Bearer ${token}`;
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: fullUrl,
        method,
        data,
        header,
        success: res => {
          console.log(`API 响应 (${method} ${url}):`, res.data);
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            // 处理错误
            console.error(`API 错误 (${method} ${url}):`, res);
            if (res.statusCode === 401) {
              // token 过期，跳转到登录页
              wx.showToast({
                title: '登录已过期，请重新登录',
                icon: 'none',
                duration: 2000
              });
              setTimeout(() => {
                wx.navigateTo({
                  url: '/pages/login/login'
                });
              }, 2000);
            }
            reject(res);
          }
        },
        fail: err => {
          console.error(`API 请求失败 (${method} ${url}):`, err);
          reject(err);
        }
      });
    });
  },

  async updateCartCount() {
    try {
      const res = await this.request({
        url: '/cart/count/',
        method: 'GET'
      });
      if (res.code === 200) {
        this.globalData.cartCount = res.data.count;
        // 触发自定义事件，通知页面更新购物车数量
        wx.eventBus.emit('cartCountChanged', res.data.count);
      }
    } catch (error) {
      console.error('获取购物车数量失败：', error);
    }
  }
});